﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;

namespace MovieApp
{
    public partial class MainWindow : Form
    {
        SettingsHandler settings;
        MovieHandler seenMovies;
        private string MoviePath;
        Process currentProcess;

        public MainWindow()
        {
            InitializeComponent();
            InitWindow();

            if (settings.SaveOnExit)
                AppDomain.CurrentDomain.ProcessExit += new EventHandler(SaveSeenMovies);
        }

        private void SaveSeenMovies(object sender, EventArgs e)
        {
            seenMovies.UpdateMovieList();
        }

        public void InitWindow()
        {
            settings = new SettingsHandler();
            seenMovies = new MovieHandler();
            MoviePath = settings.MoviePath;
            treeView1.Nodes.Clear();
            string[] elements = MoviePath.Split('\\');
            treeView1.Nodes.Add(elements[elements.Length - 1]);
            int lastBackslash = MoviePath.LastIndexOf('\\');
            MoviePath = MoviePath.Remove(lastBackslash);

            listView1.Items.Clear();

            currentProcess = new Process();
        }

        private List<ListViewItem> GetChildrenFiles(DirectoryInfo directory)
        {
            FileInfo[] files = {};
            try
            {
                files = directory.GetFiles();
            }
            catch { }

            //get seen movies
            List<ListViewItem> fileNodes = (from file in files where MovieHandler.IsMovie(file.Name) && seenMovies.MovieSeen( file.Name) select new ListViewItem(file.Name, 2)).ToList<ListViewItem>();
            //get files not seen
            fileNodes.AddRange((from file in files where MovieHandler.IsMovie(file.Name) && !seenMovies.MovieSeen(file.Name) select new ListViewItem(file.Name, 1)).ToArray<ListViewItem>());
            //get the rest of the files
            fileNodes.AddRange((from file in files where !MovieHandler.IsMovie(file.Name) select new ListViewItem(file.Name, 0)).ToArray<ListViewItem>());

            //add season and episode parsed data
            foreach (ListViewItem fileNode in fileNodes)
            {
                if (fileNode.ImageIndex == 1 || fileNode.ImageIndex == 2)
                {
                    fileNode.SubItems.Add(MovieHandler.GetSeasonNumber(fileNode.Text));
                    fileNode.SubItems.Add(MovieHandler.GetEpisodeNumber(fileNode.Text));
                    fileNode.SubItems.Add(MovieHandler.GetShowName(fileNode.Text));
                }
            }

            return fileNodes;
        }

        private List<TreeNode> GetChildrenFolders(DirectoryInfo directory)
        {
            DirectoryInfo[] subdirs = { };
            try
            {
                subdirs = directory.GetDirectories();
            }
            catch { }
            List<TreeNode> dirNodes = (from subdir in subdirs select new TreeNode(subdir.Name)).ToList<TreeNode>();

            return dirNodes;
        }

        private List<ListViewItem> GetChildrenFoldersList(DirectoryInfo directory)
        {
            DirectoryInfo[] subdirs = { };
            try
            {
                subdirs = directory.GetDirectories();
            }
            catch { }
            List<ListViewItem> dirNodes = (from subdir in subdirs select new ListViewItem(subdir.Name, 3)).ToList<ListViewItem>();

            return dirNodes;
        }


        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.Show();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsWindow st = new SettingsWindow(this);
            st.Show();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeView tv = sender as TreeView;
            TreeNode tn = tv.SelectedNode;
            string fullPath = MoviePath + '\\' + tn.FullPath;
            
            //fetch subfolders
            if (tn.Nodes.Count == 0)
            {
                tn.Nodes.AddRange(GetChildrenFolders(new DirectoryInfo(fullPath)).ToArray());
                tn.Expand();
            }

            //show files in right panel
            listView1.Items.Clear();
            listView1.Items.AddRange(GetChildrenFoldersList(new DirectoryInfo(fullPath)).ToArray());
            listView1.Items.AddRange(GetChildrenFiles(new DirectoryInfo(fullPath)).ToArray());
            listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        private void smallIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.SmallIcon;
        }

        private void largeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.LargeIcon;
        }

        private void listToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.List;
        }

        private void detailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.Details;
            listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListView lv = sender as ListView;
            ListViewItem selectedItem = lv.FocusedItem;
            string filePath = MoviePath + "\\" + treeView1.SelectedNode.FullPath + "\\" + selectedItem.Text;
            string fileName = selectedItem.Text;
            
            //if it's a folder
            if (selectedItem.ImageIndex == 3)
            {
                foreach (TreeNode tn in treeView1.SelectedNode.Nodes)
                    if (tn.Text == selectedItem.Text)
                    {
                        treeView1.SelectedNode = tn;
                        break;
                    }
            }
            else //run movie
            {
                try
                {
                    currentProcess.Kill();
                }
                catch { }
                currentProcess = Process.Start(filePath);
                
                //mark the movie as watched
                selectedItem.ImageIndex = 2;
                seenMovies.WatchMovie(fileName);
            }
        }

        private void listView1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //check if ENTER or BACKSPACE was pressed
            switch (e.KeyChar)
            {
                case (char)Keys.Return:
                    e.Handled = true;
                    ListView lv = sender as ListView;
                    ListViewItem selectedItem = lv.FocusedItem;
                    string filePath = MoviePath + "\\" + treeView1.SelectedNode.FullPath + "\\" + selectedItem.Text;
                    string fileName = selectedItem.Text;
            
                    //if it's a folder
                    if (selectedItem.ImageIndex == 3)
                    {
                        foreach (TreeNode tn in treeView1.SelectedNode.Nodes)
                            if (tn.Text == selectedItem.Text)
                            {
                                treeView1.SelectedNode = tn;
                                break;
                            }
                    }
                    else //run movie
                    {
                        try
                        {
                            currentProcess.Kill();
                        }
                        catch { }
                        currentProcess = Process.Start(filePath);
                        
                        //mark the movie as watched
                        selectedItem.ImageIndex = 2;
                        seenMovies.WatchMovie(fileName);
                    }
                    break;
                case (char)8:
                    e.Handled = true;
                    //set selected TreeNode
                    TreeNode trn = treeView1.SelectedNode;
                    if (trn.Parent != null)
                        treeView1.SelectedNode = trn.Parent;
                    break;
            }
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InitWindow();
        }
    }
}
